<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2018/12/3
 * Time: 16:09
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Counts;

class CountController extends Controller
{
    /**
     * 获取分类
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(){
        $pid = (int)request('id',0);
        $date = [
            'start' =>(string)request('start',''),
            'end' =>(string)request('end',''),
        ];

        if($pid == 0){
            $lists = Counts::where('pid',$pid)->with(['countlogpid'=>function($query)use($date){
                if ($date['start']){
                    $query->whereBetween('date',[$date['start'],$date['end']])->orderBy('id','DESC')->get();
                }
            }])->get();
            $list = array();

            foreach ($lists as $key => $item) {
                $newArr = array();
                $list[$key]['id'] = $item['id'];
                $list[$key]['name'] = $item['name'];
                if(count($item['countlogpid'])>0){
                    foreach ($item['countlogpid'] as $k => $i) {
                        if(isset($newArr[$key][$i['date']]['total'])){
                            $newArr[$key][$i['date']]['total'] += $i['total'];
                        }else{
                            $newArr[$key][$i['date']]['total'] = $i['total'];
                            $newArr[$key][$i['date']]['date'] = $i['date'];
                            $list[$key]['_dates'][] = $i['date'];
                        }
                    }
                    foreach ($newArr as $kk => $ii) {
                        foreach ($ii as $kkk => $iii) {
                            $list[$key]['total'][] = $iii;
                        }
                    }
                }else{
                    $list[$key]['total'] = [];
                }

            }
        }else{
            $list = Counts::where('pid',$pid)->get();
        }

        return $this->returnJson(0,'',$list);
    }

}
